/*
* 
* @description: Sample Socket connection with UDP
*
* @author: Dai-Yunxing
* @date: 2009-10-6
*/

#include "preh.h"
#include<WinSock.h>
using namespace std;

WORD g_rPort = 6666;
char g_rIP[16] = "127.0.0.1";
WORD g_lPort = 7777;
char g_lIP[16] = "127.0.0.1";

SOCKET g_S;
SOCKET g_S2;
//remote address
struct sockaddr_in g_rAddr;
//local address
struct sockaddr_in g_lAddr;

WSADATA g_WD;

//Display an error string and exit with code 1
void ShowInfo(char* input)
{
	puts(input);
	system("pause");
	exit(1);
}
void SetSockAddr(struct sockaddr_in *a,WORD port, char* IP)
{
	a->sin_family = AF_INET;
	a->sin_port = htons(port);
	a->sin_addr.s_addr = inet_addr(IP);
}
int main()
{
	int result;
	WORD v;
	v = 0x0101;
	result = WSAStartup(v,((LPWSADATA)&g_WD));
	if(0 != result)
		ShowInfo("wsa_start_error");
	g_S = socket(PF_INET, SOCK_DGRAM, 0);
	g_S2 = socket(PF_INET, SOCK_DGRAM, 0);
	if(SOCKET_ERROR == g_S)
		ShowInfo("socket_create_error!");
	int length = sizeof(g_rAddr);
	char msg[80];
	
	puts("Type exit to quit!");
	
	SetSockAddr(&g_lAddr,g_lPort,g_lIP);
	result = bind(g_S,(struct sockaddr far*)&g_lAddr, sizeof(g_lAddr));
	if(SOCKET_ERROR == result)
		ShowInfo("bind_error");

	SetSockAddr(&g_rAddr,g_rPort,g_rIP);
	do 
	{
		puts("Send:");
		gets(msg);
		if(!strcmp("exit",msg))
			break;
		result = sendto(g_S,msg,strlen(msg),0,(struct sockaddr far*)&g_lAddr,length);
		if(SOCKET_ERROR == result)
			ShowInfo("send_error");
		puts("Send OK!Waiting for response...");
		result = recv(g_S, msg, 80,0);
		if(SOCKET_ERROR == result)
			ShowInfo("receive_error");
		msg[result]=0;
		puts(msg);
		puts("Receive OK!");
	} while(true);

	closesocket(g_S);
	WSACleanup();
	system("pause");
	return 0;
	
}